﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.WebProvider;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Common.Enums.Data;
using ZBJF.Warranty.Common.Enums.InsuranceOrder.Data;
using ZBJF.Warranty.Model;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text;
using System.Transactions;
using ZBJF.Warranty.Model.ViewModel.Sellers;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;
using System.Collections;
using System.IO.Pipes;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model.NoFKDbEntity;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class SellerInsuranceProductsController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(InsuranceProductPackageModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceProductPackageServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.ProductPackageName,
                o.InsuranceProductPackageNO,
                o.ActiveCardInLimitDays,
                o.IsAvailable,
                CreateTime = o.CreateTime == DateTime.MinValue ? "" : o.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"),
                LastModifyTime = o.LastModifyTime == DateTime.MinValue ? "" : o.LastModifyTime.ToString("yyyy-MM-dd hh:mm:ss")
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取商户产品信息
        /// </summary>
        /// <param name="sellerId">商户</param>
        /// <param name="sellerInsuranceProductsId">商户产品</param>
        /// <returns></returns>
        public ActionResult Edit(int sellerId, int sellerInsuranceProductsId)
        {
            var sellerInsuranceProducts = ServiceFactory.SellerInsuranceProductsServiceInstance.LoadById(sellerInsuranceProductsId) ??
                                          new SellerInsuranceProducts();
            if (sellerInsuranceProducts.SellerInsuranceProductMappings == null || !sellerInsuranceProducts.SellerInsuranceProductMappings.Any())
                sellerInsuranceProducts.SellerInsuranceProductMappings = new List<SellerInsuranceProductMappings> { new SellerInsuranceProductMappings() };
            return View(sellerInsuranceProducts);
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="insuranceProductPackageId"></param>
        /// <returns></returns>
        public ActionResult Detail(int insuranceProductPackageId)
        {
            var order = ServiceFactory.InsuranceProductPackageServiceInstance.LoadByID(insuranceProductPackageId);
            return View(order);
        }
        public ActionResult ProductTagsImages(int id)
        {
            var order = ServiceFactory.SellerInsuranceProductsServiceInstance.LoadById(id);
            return View(order);
        }

        public bool IsExistSellerProduct(string sellerInsuranceProductName, long id = 0)
        {
            return ServiceFactory.SellerInsuranceProductsServiceInstance.IsExist(sellerInsuranceProductName, id);
        }

        /// <summary>
        /// 保存商户商品信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="sellerInsuranceProductTags"></param>
        /// <param name="sellerInsuranceProductImages"></param>
        /// <param name="sellerInsuranceProductMappings"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveSellerInsuranceProducts(SellerInsuranceProducts model, List<string> sellerInsuranceProductTags, List<string> sellerInsuranceProductImages, List<SellerInsuranceProductMappings> sellerInsuranceProductMappings)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            var serv = ServiceFactory.SellerInsuranceProductsServiceInstance;
            var tagServ = ServiceFactory.SellerInsuranceProductTagsServiceInstance;
            var imgServ = ServiceFactory.SellerInsuranceProductImagesServiceInstance;
            var insuranceProductServ = ServiceFactory.SellerInsuranceProductMappingsServiceInstance;

            bool status = false;
            if (model.ID > 0)
            {
                using (TransactionScope sc = new TransactionScope())
                {
                    try
                    {
                        var sellerInsuranceProductsList = serv.LoadById(model.ID);
                        sellerInsuranceProductsList.LastModifyBy = CurrentUser.UserAccount;
                        sellerInsuranceProductsList.LastModifyTime = DateTime.Now;
                        sellerInsuranceProductsList.InsuranceCompanyID = model.InsuranceCompanyID;//承保公司
                        sellerInsuranceProductsList.MaxSalesQty = model.MaxSalesQty;//库存量
                        sellerInsuranceProductsList.IdentityCardLimitQty = model.IdentityCardLimitQty;//限定数
                        sellerInsuranceProductsList.Intro = model.Intro;//内容
                        sellerInsuranceProductsList.ProductName = model.ProductName;//产品名称
                        sellerInsuranceProductsList.SaleRetailPrice = model.SaleRetailPrice;//零售价
                        sellerInsuranceProductsList.InsuranceCompanyRetailPrice = model.InsuranceCompanyRetailPrice;//销售商零售价
                        sellerInsuranceProductsList.ZBJFSalePrice = model.ZBJFSalePrice;//中保售价

                        if (serv.UpdateEntities(sellerInsuranceProductsList))
                        {
                            //添加标签
                            status = tagServ.AddTags(model.ID, sellerInsuranceProductTags);
                            //添加图片
                            status = imgServ.AddSellerInsuranceProductImages(model.ID, sellerInsuranceProductImages, CurrentUser.UserAccount);
                            //配置产品
                            status = insuranceProductServ.AddSellerInsuranceProductMappings(model.ID, sellerInsuranceProductMappings);
                        }
                        sc.Complete();
                    }
                    catch (Exception ex)
                    {
                        sc.Dispose();
                    }
                    responseResult.Success = status;
                    TempData["ResponseResult"] = responseResult;
                    return Content("<script>window.setTimeout(function(){window.close();parent.location.href = parent.location.href;},500)</script>");
                }
            }
            else
            {
                if (serv.IsExist(model.ProductName))
                {
                    responseResult.Message = "该产品名称已经存在,请修改后提交！";
                    TempData["ResponseResult"] = responseResult;
                    return Content("<script>window.close();parent.location.href = parent.location.href;</script>");
                }
                else
                {
                    using (TransactionScope sc = new TransactionScope())
                    {
                        try
                        {
                            model.CreateTime = DateTime.Now;
                            model.CreateBy = CurrentUser.UserAccount;
                            model.LastModifyBy = CurrentUser.UserAccount;
                            model.LastModifyTime = DateTime.Now;
                            model.IsCardProduct = true;
                            model.IsAvailable = true;
                            model.SellerInsuranceProductMappings = null;
                            var entity = serv.AddEntities(model);
                            if (entity.ID > 0)
                            {
                                model.SellerProductCode = CommonMethod.GenerateCode("XSSCP", entity.ID.ToString(), 6);
                                serv.UpdateEntities(model);
                                //保存标签
                                tagServ.AddTags(entity.ID, sellerInsuranceProductTags);
                                //保存图片
                                imgServ.AddSellerInsuranceProductImages(model.ID, sellerInsuranceProductImages, CurrentUser.UserAccount);
                                //保存基础产品
                                status = insuranceProductServ.AddSellerInsuranceProductMappings(entity.ID, sellerInsuranceProductMappings);
                                sc.Complete();
                            }
                        }
                        catch (Exception ex)
                        {
                            sc.Dispose();
                        }
                        responseResult.Success = status;
                        TempData["ResponseResult"] = responseResult;
                        return Content("<script>window.close();parent.location.href = parent.location.href;</script>");
                    }
                }
            }
        }

        public ActionResult AddInsuranceProducts()
        {
            return View();
        }
        #region 保险列表 JsonResult AddInsuranceProducts(InsuranceProductsModel model, InsuranceProductPackageModel model1)
        [HttpPost]
        public JsonResult AddInsuranceProducts(InsuranceProductsModel model, InsuranceProductPackageModel model1)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceProductsServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                InsuranceProductCategoryDesc ="",// EnumHelper.Instance.GetDescription(typeof(InsuranceProductCategory), o.InsuranceProductCategory),
                o.ProductName,
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"),
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd hh:mm:ss"),
                o.IsAvailable
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region
        public ActionResult AddInsuranceProductPackage(int insuranceProductPackage)
        {
            var order = ServiceFactory.InsuranceProductPackageServiceInstance.LoadByID(insuranceProductPackage);
            var obj = new Model.NoFKDbEntity.InsuranceProductPackageNOFK
            {
                InsuranceProductPackageMappings = new List<InsuranceProductPackageMappingNoPK>()
            };
            if (order != null)
            {
                obj.ID = order.ID;
                obj.ProductPackageName = order.ProductPackageName;
                obj.ActiveCardInLimitDays = order.ActiveCardInLimitDays;
                foreach (var item in order.InsuranceProductPackageMapping)
                {
                    if (item == null) continue;
                    obj.InsuranceProductPackageMappings.Add(new Model.NoFKDbEntity.InsuranceProductPackageMappingNoPK
                    {
                        InsuranceProductPackageId = item.InsuranceProductPackageId,
                        InsuranceProductId = item.InsuranceProductId,
                        InsuranceProductName = item.InsuranceProducts.ProductName,
                    });
                }
            }
            else
            {
                obj.InsuranceProductPackageMappings.Add(new InsuranceProductPackageMappingNoPK());
            }
            return View(obj);
        }

        [HttpPost]
        public ActionResult SaveInsuranceProductPackage(Model.NoFKDbEntity.InsuranceProductPackageNOFK model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            using (TransactionScope sc = new TransactionScope())
            {
                if (model.ID > 0)
                {
                    try
                    {
                        var serv = ServiceFactory.InsuranceProductPackageServiceInstance;
                        var entity = serv.LoadByID(model.ID);
                        entity.ProductPackageName = model.ProductPackageName;
                        entity.ActiveCardInLimitDays = model.ActiveCardInLimitDays;
                        entity.LastModifyTime = DateTime.Now;
                        entity.LastModifyBy = CurrentUser.UserAccount;
                        if (serv.UpdateEntities(entity))
                        {
                            var servMapp = ServiceFactory.InsuranceProductPackageMappingServiceInstance;
                            List<long> ippmids = new List<long>();
                            foreach (var item in model.InsuranceProductPackageMappings)
                            {
                                long id = item.InsuranceProductId;
                                var entity1 =
                                    servMapp.LoadEntities(
                                        m => m.InsuranceProductPackageId == model.ID && m.InsuranceProductId == id)
                                        .AsNoTracking()
                                        .FirstOrDefault();
                                if (entity1 != null)
                                {
                                    ippmids.Add(item.InsuranceProductId);
                                    InsuranceProductPackageMapping entity2 = new InsuranceProductPackageMapping();
                                    entity2.InsuranceProductId = item.InsuranceProductId;
                                    entity2.ID = entity1.ID;
                                    entity2.InsuranceProductPackageId = entity1.InsuranceProductPackageId;
                                    servMapp.UpdateEntities(entity2);
                                }
                                else
                                {
                                    ippmids.Add(item.InsuranceProductId);
                                    servMapp.AddEntities(new InsuranceProductPackageMapping
                                    {
                                        InsuranceProductId = item.InsuranceProductId,
                                        InsuranceProductPackageId = entity.ID
                                    });
                                }
                            }
                            if (ippmids.Any())
                            {
                                servMapp.DeleteBy(model.ID, ippmids);
                            }
                            sc.Complete();
                            responseResult.Success = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        responseResult.Message = ex.Message;
                    }
                    finally
                    {
                        sc.Dispose();
                    }
                }
                else
                {
                    try
                    {
                        var serv = ServiceFactory.InsuranceProductPackageServiceInstance;
                        if (serv.IsExist(model.ProductPackageName))
                        {
                            responseResult.Message = "该产品名称已经存在,请修改后提交！";
                        }
                        else
                        {
                            var entity = new InsuranceProductPackage
                            {
                                ProductPackageName = model.ProductPackageName,
                                IsAvailable = true,
                                CreateTime = DateTime.Now,
                                CreateBy = CurrentUser.UserAccount,
                                LastModifyTime = DateTime.Now,
                                LastModifyBy = CurrentUser.UserAccount,
                                InsuranceProductPackageNO = CommonMethod.GetTimeStamp()
                            };
                            var ret = serv.AddEntities(entity);
                            if (ret.ID > 0)
                            {
                                var servMapp = ServiceFactory.InsuranceProductPackageMappingServiceInstance;
                                for (int i = 0; i < model.InsuranceProductPackageMappings.Count; i++)
                                {
                                    servMapp.AddEntities(new InsuranceProductPackageMapping
                                    {
                                        InsuranceProductId = model.InsuranceProductPackageMappings[i].InsuranceProductId,
                                        InsuranceProductPackageId = entity.ID
                                    });
                                }
                                responseResult.Success = entity.ID > 0;
                            }
                            sc.Complete();
                        }

                    }
                    catch (Exception ex)
                    {
                        responseResult.Message = ex.Message;
                    }
                    finally
                    {
                        sc.Dispose();
                    }
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("Index", "SellerInsuranceProducts");
        }

        #endregion
        #region 修改状态
        [HttpPost]
        public JsonResult UpdateInsuranceProductPackageStatus(int id, bool isAvailable)
        {
            var serv = ServiceFactory.InsuranceProductPackageServiceInstance;
            var entity = serv.LoadByID(id);
            bool status = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                status = serv.UpdateEntities(entity);
            }
            return Json(new
            {
                success = status,
                message = status ? "修改成功!" : "修改失败!"
            });
        }
        #endregion
        #region 销售商产品
        public ActionResult SellerInsuranceProducts()
        {
            return View();
        }
        [HttpPost]
        public JsonResult SellerInsuranceProducts(SellerInsuranceProductsModel model)
        {
            var total = 0;
            var list = ServiceFactory.SellerInsuranceProductsServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.SellerId,
                InsuranceProductId = o.SellerInsuranceProductMappings.Any() ? o.SellerInsuranceProductMappings.First().InsuranceProductId : 0,
                InsuranceProductPackageID = o.SellerInsuranceProductMappings.Any() ? o.SellerInsuranceProductMappings.First().InsuranceProductPackageID : 0,
                o.InsuranceCompanyID,
                CompanyName = o.InsuranceCompanyID.HasValue ? o.InsuranceCompany.CompanyName : "",
                ParentCompanyName = o.InsuranceCompanyID.HasValue ? o.InsuranceCompany.ParentCompanyName : "",
                o.Sellers.SellersName,
                o.ProductName,
                o.SaleRetailPrice,
                o.InsuranceCompanyRetailPrice,
                o.ZBJFSalePrice,
                o.MaxSalesQty,
                o.IdentityCardLimitQty,
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"),
                o.IsAvailable
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 修改销售商产品状态
        [HttpPost]
        public JsonResult UpdateSellerInsuranceProductsStatus(int id, bool isAvailable)
        {
            var serv = ServiceFactory.SellerInsuranceProductsServiceInstance;
            var entity = serv.LoadById(id);
            bool status = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                status = serv.UpdateEntities(entity);
            }
            return Json(new
            {
                success = status,
                message = status ? "成功" : "失败"
            });
        }

        #endregion
    }
}